<?php

namespace backend\controllers;

use backend\controllers\RbacController;
use backend\models\OperForm;
use backend\models\TauRoleinfo;
use yii\helpers\ArrayHelper;
use backend\models\TauOperinfo;
use yii\base\Exception;
use backend\models\AuthAssignment;
use backend\models\TbaLoginfo;
use backend\models\TmeOrderinfo;
use backend\models\TmeOutstockinfo;
use backend\models\TmeInstockinfo;
/**
 * #name=操作员管理模块#
 */
class OperatorController extends RbacController {
	public $layout='ace';		
	/**
	 * #operation=添加操作员#
	 */
	public function actionAdd(){		
		$model=new OperForm();
		$model->scenario='addoperator';
		$role=TauRoleinfo::findAll(['State'=>1]);
		$roledata=ArrayHelper::map($role, 'ID', 'RoleName');
		//判断是否提交
		if(\Yii::$app->request->isPost){
			$model->attributes=\Yii::$app->request->post('OperForm');//表单赋值
			//表单验证
			if($model->validate()){
				//进行数据的写入
				$operator=new TauOperinfo();
				$operator->attributes=$model->attributes;
				$operator->TAu_ID=$model->RoleID;
				$taurole=TauRoleinfo::findOne(['ID'=>$operator->TAu_ID]);
				$operator->RoleName=$taurole->RoleName;
				$operator->auth_key=\Yii::$app->security->generateRandomString();
				$operator->Pwd=substr(md5($model->Pwd.$operator->auth_key), 9,12);//密码进行md5加密截取
				if($operator->save()){
					//进行rbac权限控制
					$auth=\Yii::$app->authManager;
					//获取操作员id
					$operid=$operator->getId();					
					$authname=$auth->getRole($operator->RoleName);//获取角色
					$auth->assign($authname, $operid);//将操作员赋予角色										
					$this->redirect(['operator/add']);
				}else{
					//var_dump($operator->errors);exit;
					throw new Exception('数据写入失败', '404');
				}
			}
		}
		$tableid=1;
		return $this->render('index',[
				'model'=>$model,
				'roledata'=>$roledata,
				'tableid'=>$tableid
		]);
	}
	
	/**
	 * #operation=操作员列表#
	 */
	public function actionMemberlist(){
		$tableid=0;
		return $this->render('index',['tableid'=>$tableid]);
	}
	
	/**
	 * #operation=操作员列表数据异步获取#
	 */
	public function actionTablesdata(){	
			
			$start=\Yii::$app->request->post('start');//开始条数
			
			$length=\Yii::$app->request->post('length');//长度
			
			$column=\Yii::$app->request->post('order')[0]['column'];//排序列
			
			$columnArray=[
				'1'=>'OperID',
				'2'=>'username'
			];
			$columnName=$columnArray[$column];
			
			$order=\Yii::$app->request->post('order')[0]['dir'];//排序方式
			
			$draw=\Yii::$app->request->post('draw');//当前页码
			if(!empty(\Yii::$app->request->post('search')['value'])){
				$search=\Yii::$app->request->post('search')['value'];
				$where="username like '%".$search."%' or RoleName like '%".$search."%' or Address like '%".$search."%'";
			}else{
				$where="";
			}
			
			
			//查询操作员信息
			$operator=TauOperinfo::find()->where($where)->orderBy($columnName,$order)->offset($start)->limit($length)->asArray()->all();
			
			//查询操作员总个数
			$operatorcount=TauOperinfo::find()->where($where)->count();
			
			$data=[];
			//进行数据构造
			foreach ($operator as $o){
				$dataArray=[];
				$dataArray['checkbox']='<center><label class="pos-rel"><input type="checkbox" class="ace"><span class="lbl"></span></label></center>';
				$dataArray['operid']=$o['OperID'];
				
				$dataArray['opername']=$o['username'];
				
				$dataArray['rolename']=$o['RoleName'];
				
				$dataArray['address']=$o['Address'];
				
				$dataArray['linktel']=$o['LinkTel'];
				
				$dataArray['email']=$o['Email'];
				
				$dataArray['options']="<div class=\"hidden-sm hidden-xs action-buttons\">	
					<a class=\"green\" onclick=\"update(".$o['ID'].")\">
						<i class=\"ace-icon fa fa-pencil bigger-130\"></i>
					</a>
	
					<a class=\"red\" onclick=\"javascript:return show_confirm(".$o['ID'].")\">
						<i class=\"ace-icon fa fa-trash-o bigger-130\"></i>
					</a>
				</div>";
				$data[]=$dataArray;
			}
			
			$temp=[
				'draw'=>$draw,
				'recordsTotal'=>$operatorcount,
				'recordsFiltered'=>$operatorcount,
				'data'=>$data
			];
			return json_encode($temp);				
	}
	
	/**
	 * #operation=操作员信息修改#
	 */
	public function actionUpdate(){
		
		//判断是否传递id
		if(\Yii::$app->request->post('id')){
			$id=\Yii::$app->request->post('id');
			
			$updateOper=new OperForm(['scenario'=>'update']);
			//查询传递id值对应的操作员信息
			$opermsg=TauOperinfo::findOne(["ID"=>$id]);
			//查询搜有角色
			$role=TauRoleinfo::find()->where(['State'=>1])->all();
			$roledata=ArrayHelper::map($role, 'ID', 'RoleName');
			
			return $this->renderPartial('_update',[
					'model'=>$updateOper,
					'id'=>$id,
					'username'=>$opermsg->username,
					'roledata'=>$roledata,
					'roleid'=>$opermsg->TAu_ID,
					'RoleName'=>$opermsg->RoleName,
					'Pwd'=>$opermsg->Pwd,
					'Address'=>$opermsg->Address,
					'LinkTel'=>$opermsg->LinkTel,
					'QQ'=>$opermsg->QQ,
					'Email'=>$opermsg->Email,
					'Mobile'=>$opermsg->Mobile,
					'SortID'=>$opermsg->SortID,
					'State'=>$opermsg->State
			]);
		}
		//判断是否有修改动作
		if(\Yii::$app->request->isPost){
			$operid=\Yii::$app->request->post('operid');
			$updateAR=TauOperinfo::findOne(['ID'=>$operid]);
			$updateForm=new OperForm(['scenario'=>'update']);
			$updateForm->attributes=\Yii::$app->request->post('OperForm');
			if($updateForm->validate()){
				$updateAR->attributes=$updateForm->attributes;
				//判断表单提交的密码是否改变，如果改变进行加密
				 if($updateAR->Pwd ==$updateForm->Pwd){
					$updateAR->Pwd =$updateForm->Pwd;
				}else{
					$updateAR->Pwd=substr(md5(trim($updateForm->Pwd.$updateAR->auth_key)), 9,12);
				} 
				
				$updateAR->TAu_ID=$updateForm->RoleID;
				$updateRolename=TauRoleinfo::findOne(['ID'=>$updateAR->TAu_ID]);
				$updateAR->RoleName=$updateRolename->RoleName;
				if($updateAR->save()){
					$this->redirect(['operator/add']);
				}else{
					var_dump($updateAR->errors);exit;
					throw new \Exception('数据修改失败', '404');
				}
			}else{
				$key=array_keys($updateForm->errors);
				foreach ($key as $k){					
					exit("<script>alert(\"".$updateForm->errors[$k][0]."\");window.history.go(-1);</script>");
				}
			}

		}
		
	}

	
	/**
	 * #operation=操作员删除#
	 */
	public function actionDel(){
		if(\Yii::$app->request->post('action') && \Yii::$app->request->post('action')=="delete"){
			$id=\Yii::$app->request->post('id');
			$deloper=TauOperinfo::findOne(['ID'=>$id]);//查找要删除的操作员
			$connect=\Yii::$app->db;
			$transcation=$connect->beginTransaction();
			try {
				//查找与操作员相关的授权信息表
				$authassign=AuthAssignment::findOne(['user_id'=>$id]);
				 if($authassign !=null){
					if($authassign->delete()){
						$authassign->delete();
					}else{
						throw new Exception('操作员授权信息删除失败',1);
					}
				} 
				//查找与操作员相关的日志信息表
			 	$operlog=TbaLoginfo::find()->where(['TAu_ID'=>$id]);			 	
				$operlogcount=$operlog->count();
				if($operlogcount !=0){
					if(TbaLoginfo::deleteAll(['TAu_ID'=>$id]) !=0){
						TbaLoginfo::deleteAll(['TAu_ID'=>$id]);
					}else{						
						throw new Exception('操作员日志信息删除失败',2);
					}
				} 
				//查询与操作员相关的订单信息表
				$operorder=TmeOrderinfo::find()->where(['TAu_ID'=>$id]);
				$operordercount=$operorder->count();
				if($operordercount !=0){
					if(TmeOrderinfo::deleteAll(['TAu_ID'=>$id]) !=0){
						TmeOrderinfo::deleteAll(['TAu_ID'=>$id]);
					}else{
						throw new Exception('操作员订单信息删除失败','3');
					}
				}
				//查询与操作员相关的出库信息表
				$operoutstock=TmeOutstockinfo::find()->where(['TAu_ID'=>$id]);
				$operoutstockcount=$operoutstock->count();
				if($operoutstockcount != 0){
					if(TmeOutstockinfo::deleteAll(['TAu_ID'=>$id]) != 0){
						TmeOutstockinfo::deleteAll(['TAu_ID'=>$id]);
					}else{
						throw new Exception('操作员出库信息删除失败','4');
					}
				}
				//查询与操作员相关的入库信息表
				$operinstock=TmeInstockinfo::find()->where(['TAu_ID'=>$id]);
				$operinstockcount=$operinstock->count();
				if($operinstockcount !=0){
					if(TmeInstockinfo::deleteAll(['TAu_ID'=>$id])!=0){
						TmeInstockinfo::deleteAll(['TAu_ID'=>$id]);
					}else{
						throw new Exception('操作员入库信息删除失败','5');
					}
				}
				//查询id对应的操作员表信息
				$deloper=TauOperinfo::findOne(['ID'=>$id]);
				if($deloper->delete() !=0){
					$deloper->delete();
					$this->redirect(['operator/add']);
				}else{
					throw new Exception('操作员信息删除失败','');
				}
				
				$transcation->commit();
			} catch (Exception $e) {
				$transcation->rollBack();
			}
		}
	}
}

?>